using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 修改生产信息命令处理器
    /// </summary>
    public class UpdateProductionInfoCommandHandler : IRequestHandler<UpdateProductionInfoCommand, APIResult<ProductionInfoDTO>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;
        private readonly ILogger<UpdateProductionInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">生产信息仓储</param>
        /// <param name="logger">日志</param>
        public UpdateProductionInfoCommandHandler(
            IBaseRepositroy<ProductionInfo> productionInfoRepository,
            ILogger<UpdateProductionInfoCommandHandler> logger)
        {
            _productionInfoRepository = productionInfoRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改生产信息命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>修改结果</returns>
        public async Task<APIResult<ProductionInfoDTO>> Handle(UpdateProductionInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始修改生产信息，ID：{Id}", request.Id);

                // 查找生产信息
                var productionInfo = await _productionInfoRepository.GetByIdAsync(request.Id)
                    .FirstOrDefaultAsync(p => !p.IsDeleted, cancellationToken);

                if (productionInfo == null)
                {
                    _logger.LogWarning("要修改的生产信息不存在或已删除，ID：{Id}", request.Id);
                    return new APIResult<ProductionInfoDTO>
                    {
                        Code = ResultCode.更新失败,
                        Message = $"要修改的生产信息不存在或已删除，ID：{request.Id}"
                    };
                }

                // 更新生产信息
                productionInfo.BatchNumber = request.BatchNumber;
                productionInfo.ShelfLifeDays = request.ShelfLifeDays;
                productionInfo.ProductionLicenseNumber = request.ProductionLicenseNumber;
                productionInfo.ManufacturerName = request.ManufacturerName;
                productionInfo.CoverImageUrl = request.CoverImageUrl;
                productionInfo.GoodsId = request.GoodsId;
                productionInfo.ModifiedBy = request.ModifiedBy;
                productionInfo.ModifiedTime = DateTime.Now;

                // 更新到数据库
                _productionInfoRepository.Update(productionInfo);
                await _productionInfoRepository.SaveAsync();

                _logger.LogInformation("成功修改生产信息，ID：{Id}", request.Id);

                // 转换为DTO
                var productionInfoDTO = new ProductionInfoDTO
                {
                    Id = productionInfo.Id,
                    BatchNumber = productionInfo.BatchNumber,
                    ShelfLifeDays = productionInfo.ShelfLifeDays,
                    ProductionLicenseNumber = productionInfo.ProductionLicenseNumber,
                    ManufacturerName = productionInfo.ManufacturerName,
                    CoverImageUrl = productionInfo.CoverImageUrl,
                    GoodsId = productionInfo.GoodsId,
                    CreatedTime = productionInfo.CreatedTime,
                    ModifiedTime = productionInfo.ModifiedTime
                };

                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.更新成功,
                    Message = "修改生产信息成功",
                    Data = productionInfoDTO
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改生产信息时发生错误，ID：{Id}", request.Id);
                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.更新失败,
                    Message = $"修改生产信息失败: {ex.Message}"
                };
            }
        }
    }
} 